<template>
<div>
    <el-dialog title="上传图片" :visible.sync="dialog.pic.visible" width="800px">
        <div class="dialog">
            <div class="tips">
                *图片尺寸750像素*380像素，文件小于2M<br />
                *图片需保证清晰，不允许出现第三方logo、链接、二维码、与产品无关的文字、水印等。<br />
                *所有轮播主图不得拼接，不得出现任何形式的边框。第一张主图不得包含促销、夸大描述类信息，该类信息包括但不限于限时折扣、包邮、X折、满X送X等。第二张轮播主图必须为无任何logo、文字描述的纯图。
            </div>
            <div class="upload">
                <div class="action">
                    <div class="btn">
                        <el-upload :action="uploadApi" :disabled="dialog.pic.list.length == 5" :before-upload="beforeAvatarUpload" :headers="uploadHeaders" :on-success="uploadPicSuccess" accept=".jpg,.jpeg,.png" :show-file-list="false">
                            <el-button :disabled="dialog.pic.list.length == 5" size="small" type="plain" icon="el-icon-upload2">点击上传</el-button>
                        </el-upload>
                    </div>
                    <div class="msg">还可以选择{{5-dialog.pic.list.length}}张图片</div>
                </div>
                <div class="preview">
                    <div class="item" v-for="(item, idx) in dialog.pic.list">
                        <i class="el-icon-close" @click="dialog.pic.list.splice(idx, 1)"></i>
                        <img :src="item.url">
                    </div>
                </div>
            </div>
            <el-checkbox v-model="dialog.pic.checked">请确保需要上传的图片已获取版权资质，因上传图片版权问题而使游品库遭受相关损失，应由供应商承担全部责任</el-checkbox>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitPicDialog">上传</el-button>
            <el-button @click="dialog.pic.visible = false">取 消</el-button>
        </span>
    </el-dialog>

    <el-dialog title="上传图片" :visible.sync="dialog.share.visible" width="800px">
        <div class="dialog">
            <div class="tips">
                *只能上传一张海报，尺寸于750像素*1200像素，文件小于2M<br />
                *图片需保证清晰，不允许出现第三方logo、链接、二维码、与产品无关的文字、水印等。
            </div>
            <div class="upload">
                <div class="action">
                    <div class="btn">
                        <el-upload :action="uploadApi" :headers="uploadHeaders" :before-upload="beforeAvatarUpload" :on-success="uploadShareSuccess" accept=".jpg,.jpeg,.png" :show-file-list="false">
                            <el-button size="small" type="plain" icon="el-icon-download">选择海报</el-button>
                        </el-upload>
                    </div>
                    <div class="msg">再次上传海报将替换原有海报</div>
                </div>
                <div class="preview">
                    <div class="item" v-if="dialog.share.url != ''">
                        <i class="el-icon-close" @click="dialog.share.url = ''"></i>
                        <img :src="dialog.share.url">
                    </div>
                </div>
            </div>
            <el-checkbox v-model="dialog.share.checked">请确保需要上传的图片已获取版权资质，因上传图片版权问题而使游品库遭受相关损失，应由供应商承担全部责任</el-checkbox>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitShareDialog">上传</el-button>
            <el-button @click="dialog.share.visible = false">取 消</el-button>
        </span>
    </el-dialog>

    <el-dialog title="上传视频" :visible.sync="dialog.video.visible" width="800px">
        <div class="dialog">
            <div class="tips">
                *最多可上传1个视频，视频需小于30M，限MP4格式
            </div>
            <div class="upload">
                <div class="action">
                    <div class="btn">
                        <el-upload :action="uploadApi" :headers="uploadHeaders" :before-upload="beforeAvatarUploadVideo" accept=".mp4" :on-progress="videoUploading" :on-success="uploadVideoSuccess" :show-file-list="false">
                            <el-button size="small" type="plain" icon="el-icon-download">选择视频</el-button>
                        </el-upload>
                    </div>
                    <div class="msg">再次上传海报将替换原有视频</div>

                </div>
                <div v-if="showVideoLoading" style="margin-top: 10px;">(视频上传中，请稍后...)</div>
                <div class="preview">
                    <div class="item" v-if="dialog.video.url != ''">
                        <i class="el-icon-close" @click="dialog.video.url = ''"></i>
                        <div class="v">
                            <i class="el-icon-video-camera"></i>
                        </div>
                    </div>
                </div>
            </div>
            <el-checkbox v-model="dialog.video.checked">请确保需要上传的视频已获取版权资质，因上传图片版权问题而使游品库遭受相关损失，应由供应商承担全部责任</el-checkbox>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitVideoDialog">上传</el-button>
            <el-button @click="dialog.video.visible = false">取 消</el-button>
        </span>
    </el-dialog>

    <el-form :model="form" size="small" :rules="rules" ref="form" label-width="120px">

        <div class="panel">
            <div class="hd required">基本信息</div>
            <div class="bd">
                <div class="fm-short">
                    <el-form-item label="产品名称:" prop="name">
                        <el-input v-model.trim="form.name" placeholder="如：上海外滩+杭州西湖  最多45个字" maxlength="45" show-word-limit></el-input>
                    </el-form-item>
                    <el-form-item label="出发地:" prop="departureIdList">
                        <el-cascader :show-all-levels="false" style="width: 480px;" placeholder="添加出发地" clearable v-model="form.departureIdList" :props="cascaderProp" :options="region"></el-cascader>
                    </el-form-item>
                    <el-form-item label="目的地:" prop="destinationIdList">
                        <el-cascader style="width: 480px;" placeholder="添加目的地" clearable v-model="form.destinationIdList" :props="cascaderProp" :options="region"></el-cascader>
                    </el-form-item>
                </div>
            </div>
        </div>
        <div class="panel">
            <div class="hd required">产品图片</div>
            <div class="bd">
                <div class="upload">
                    <div class="action">
                        <div class="btn">
                            <el-button size="small" type="plain" @click="openPicDialog" icon="el-icon-upload2">上传图片</el-button>
                        </div>
                        <div class="msg">支持上传1~5张图片</div>
                    </div>
                    <div class="preview">
                        <div class="item" v-for="(item, idx) in form.pictureList">
                            <i class="el-icon-close" @click="form.pictureList.splice(idx, 1)"></i>
                            <img :src="item.url">
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!--<div class="panel">
            <div class="hd">分享海报</div>
            <div class="bd">
                <div class="upload">
                    <div class="action">
                        <div class="btn">
                            <el-button size="small" type="plain" @click="openShareDialog" icon="el-icon-upload2">上传图片</el-button>
                        </div>
                        <div class="msg">只能上传一张图片，尺寸于750像素*1200像素，文件小于2M</div>
                    </div>
                    <div class="preview">
                        <div class="item" v-if="form.sharePoster">
                            <i class="el-icon-close" @click="form.sharePoster = ''"></i>
                            <img :src="form.sharePoster">
                        </div>
                    </div>
                </div>
            </div>
        </div>-->
        <div class="panel">
            <div class="hd">产品视频</div>
            <div class="bd">
                <div class="upload">
                    <div class="action">
                        <div class="btn">
                            <el-button size="small" type="plain" @click="openVideoDialog" icon="el-icon-upload2">上传视频</el-button>
                        </div>
                        <div class="msg">最多可上传1个视频，视频需小于15M,限MP4格式</div>
                    </div>
                    <div class="preview">
                        <div class="item" v-if="form.video != ''">
                            <i class="el-icon-close" @click="form.video = ''"></i>
                            <video class="v" :src="form.video" controls="controls"></video>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!--<div class="panel" v-show="false">
            <div class="hd">供应商信息</div>
            <div class="bd">
                <div class="fm-short">
                    <el-form-item label="供应商:">
                        {{supplierName}}
                    </el-form-item>
                    <el-form-item label="联系人：" prop="supplierContacts">
                        <el-input v-model.trim="form.supplierContacts" placeholder="请输入联系人姓名"></el-input>
                    </el-form-item>
                    <el-form-item label="联系人电话：" prop="supplierPhone" style="margin-bottom: 0;">
                        <div class="contact-item" v-for="item in form.supplierPhone" :key="index">
                            <div class="it">
                                <el-input class="phone" v-model.trim="p1" readonly placeholder="中国大陆(86+)"></el-input>
                            </div>
                            <div class="it2">
                                <el-input v-model.trim="item[0]" placeholder="手机号或固话（区号+号码）"></el-input>
                            </div>
                            <div class="it">
                                <el-input v-model.trim="item[1]" placeholder="分机号"></el-input>
                            </div>
                            <div class="it3">
                                <el-button type="text" v-if="form.supplierPhone.length>1" @click="form.supplierPhone.splice(index, 1)">删除</el-button>
                            </div>

                        </div>
                    </el-form-item>
                    <el-form-item label=" ">
                        <el-button icon="el-icon-plus" type="text" @click="addPhone">添加联系人电话</el-button>
                    </el-form-item>
                </div>
            </div>
        </div>-->

    </el-form>
</div>
</template>

<script>
import Cookies from 'js-cookie'
export default {
  props: ['prodId', 'data', 'region'],
  data () {
    return {
      loading: false,
      showVideoLoading: false,
      supplierName: '',
      uploadApi: `${window.SITE_CONFIG.apiURL}/sys/oss/upload`,
      uploadHeaders: {
        token: Cookies.get('token') || ''
      },
      fileList: [],
      dialog: {
        pic: {
          visible: false,
          checked: false,
          list: []
        },
        share: {
          visible: false,
          checked: false,
          url: ''
        },
        video: {
          visible: false,
          checked: false,
          url: ''
        }
      },
      p1: '中国大陆(86+)',
      cascaderProp: {
        value: 'id',
        children: 'cities',
        label: 'name',
        multiple: true,
        checkStrictly: true
      },
      form: {
        name: '',
        departureIdList: [],
        destinationIdList: [],
        pictureList: [],
        sharePoster: '',
        video: '',
        supplierContacts: '',
        supplierPhone: [
          ['', '']
        ]
      },
      rules: {
        name: [{
          required: true,
          message: '请输入线路名称',
          trigger: 'blur'
        }],
        pictureList: [{
          required: true,
          message: '请上传产品图片',
          trigger: 'blur'
        }]
      },
      dict: {
        region: []
      }
    }
  },
  created () {
    this.$nextTick(() => {
      console.log('打印rrrrrr', this.data)
      this.getDict()
      this.initData()
    })
  },
  watch: {
    data () {
      this.$nextTick(() => {
        this.getDict()
        this.initData()
      })
    }
  },
  methods: {
    // 控制上传文件的大小
    beforeAvatarUpload (file) {
      const permitFileType = ['image/jpeg', 'image/png', 'image/jpg']
      const isJPG = permitFileType.indexOf(file.type) !== -1
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是jpeg，png或jpg格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    beforeAvatarUploadVideo (file) {
      const isLimit15 = file.size / 1024 / 1024 < 30
      if (!isLimit15) {
        this.$message.error('上传视频大小不能超过 30MB!')
      }
      return isLimit15
    },
    initData () {
      const {
        destinationList,
        departureList,
        customization,
        pictureList = []
      } = this.data
      const {
        name,
        sharePoster,
        video,
        supplierPhone = '',
        supplierContacts
      } = customization
      const departureIdList = departureList.map(item => {
        if (item.nodes) {
          return item.nodes.split(',')
        }
      })
      const destinationIdList = destinationList.map(item => {
        if (item.nodes) {
          return item.nodes.split(',')
        }
      })
      if (supplierPhone !== null) {
        const phone = supplierPhone.split(',').map(item => {
          if (item.indexOf('-') === -1) {
            return [item, '']
          }
          return item.split('-')
        })
      }
      this.form = {
        departureIdList,
        name,
        destinationIdList,
        pictureList,
        sharePoster,
        video //,
        // supplierContacts,
        // supplierPhone: phone
      }
    },
    picPreview (url) {},
    uploadPicSuccess (res, file, filelist) {
      this.dialog.pic.list.push({
        url: res.data.src
      })
    },
    uploadShareSuccess (res, file, filelist) {
      this.dialog.share.url = res.data.src
    },
    videoUploading (res, file, filelist) {
      const isLimit15 = file.size / 1024 / 1024 < 30
      if (!isLimit15) {
        this.showVideoLoading = false
      }
      this.showVideoLoading = true
    },
    uploadVideoSuccess (res, file, filelist) {
      this.showVideoLoading = false
      this.dialog.video.url = res.data.src
    },
    openVideoDialog () {
      this.dialog.video.url = this.form.video
      this.dialog.video.visible = true
    },
    submitVideoDialog () {
      if (!this.dialog.video.checked) {
        this.$message({
          message: '请勾选责任协议后提交上传',
          type: 'warning'
        })
        return
      }
      this.form.video = this.dialog.video.url
      this.dialog.video.visible = false
    },
    openShareDialog () {
      this.dialog.share.url = this.form.sharePoster
      this.dialog.share.visible = true
    },
    submitShareDialog () {
      if (!this.dialog.share.checked) {
        this.$message({
          message: '请勾选责任协议后提交上传',
          type: 'warning'
        })
        return
      }
      this.form.sharePoster = this.dialog.share.url
      this.dialog.share.visible = false
    },
    openPicDialog () {
      this.dialog.pic.list = this.form.pictureList
      this.dialog.pic.visible = true
    },
    submitPicDialog () {
      if (!this.dialog.pic.checked) {
        this.$message({
          message: '请勾选责任协议后提交上传',
          type: 'warning'
        })
        return
      }
      this.form.pictureList = [...this.dialog.pic.list]
      this.dialog.pic.visible = false
    },
    getDict () {
      Promise.all([this.$http.get('/sys/region/region')]).then(values => {
        const region = values[0].data.data
        region.map(value => {
          value.disabled = true
        })
        this.region = region
      })
    },
    addPhone () {
      this.form.supplierPhone.push(['', ''])
    },
    submit () {
      // 验证信息完整度
      const form = this.form
      if (!form.name) {
        return this.$message.error('请输入产品名称!')
      }
      if (!form.pictureList || form.pictureList.length == 0) {
        return this.$message.error('请上传产品图片!')
      }
      // if (!form.video) {
      //     return this.$message.error('请上传产品视频!')
      // }
      const sd = JSON.parse(JSON.stringify(this.form))
      sd.id = this.prodId
      const phones = []
      for (const i in sd.supplierPhone) {
        phones.push(sd.supplierPhone[i][0] + '-' + sd.supplierPhone[i][1])
      }
      sd.supplierPhone = phones.join(',')
      const d1list = []
      sd.departureIdList.map(item => {
        const id = item[item.length - 1]
        d1list.push({
          customizationId: this.prodId,
          nodes: item.join(','),
          areaId: id
        })
      })
      const d2list = []
      sd.destinationIdList.map(item => {
        const id = item[item.length - 1]
        d2list.push({
          customizationId: this.prodId,
          nodes: item.join(','),
          areaId: id
        })
      })

      sd.pictureList = sd.pictureList.map((item, index) => {
        return {
          url: item.url,
          customizationId: this.prodId
        }
      })
      sd.departureList = d1list
      sd.destinationList = d2list
      this.loading = true
      const category = this.data.customization ? this.data.customization.category : ''
      this.$http
        .put('/customization/base', {
          category: category,
          ...sd
        })
        .then(res => {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.loading = false
          const nextId = 2
          this.$emit('changeSubMenu', nextId)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.phone {
    min-width: 120px;
}

.dialog {
    .tips {
        background: #f5f5f5;
        padding: 20px;
    }

    .upload {
        padding: 20px 0;
    }
}

.hd.required::before {
    content: "*";
    color: #f56c6c;
    margin-right: 4px;
}
.contact-item {
    display: flex;
    margin-bottom: 10px;

    .it {
        flex: 1;
    }

    .it2 {
        flex: 2;
        margin: 0 20px;
    }

    .it3 {
        width: 30px;
        margin-left: 20px;
    }
}

.upload {
    .action {
        display: flex;

        .btn {
            width: 120px;
        }

        .msg {
            flex: 1;
            color: #666;
            line-height: 32px;
        }
    }

    .preview {
        display: flex;
        padding-top: 20px;
        video {
            width: 100%;
        }
        .item {
            position: relative;
            margin-right: 10px;
            width: 180px;

            i.el-icon-close {
                position: absolute;
                width: 14px;
                height: 14px;
                border-radius: 50%;
                background: #666666;
                color: #fff;
                line-height: 14px;
                text-align: center;
                right: -7px;
                top: -7px;
            }

            .v {
                text-align: center;
                cursor: pointer;
                height: 120px;
                line-height: 156px;
                background: #f7f7f7;

                i {
                    font-size: 64px;
                    color: #666;
                }
            }

            img {
                width: 100%;
            }
        }
    }
}
</style>
